package com.cskaoyan.gateway.controller.shopping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.cskaoyan.gateway.cache.CacheManager;
import com.google.common.util.concurrent.RateLimiter;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.shopping.IHomeService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.dto.HomePageResponse;
import com.mall.shopping.dto.PanelDto;
import com.mall.user.annotation.Anoymous;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.Set;

@RestController
@RequestMapping("/shopping")
public class HomePageController {

    @Reference(timeout = 3000,check = false)
    IHomeService iHomeService;
    @Autowired
    CacheManager cacheManager;
    private RateLimiter rateLimiter;


        @PostConstruct
        public void init(){

            // 表示每秒产生 100 个令牌
            rateLimiter = RateLimiter.create(500);
        }
    @Anoymous
    @GetMapping("homepage")
    public ResponseData homePage(){
        rateLimiter.acquire();

        String key = "homepage_cache";
        String cache = cacheManager.checkCache(key);
        Set<PanelDto> result = JSON.parseObject(cache,new TypeReference<Set<PanelDto>>(){});
        if (cache != null) {
            return new ResponseUtil<>().setData(result);
        }


        HomePageResponse homePageResponse = iHomeService.homepage();

        String value = JSON.toJSONString(homePageResponse.getPanelContentItemDtos());

        cacheManager.setCache(key,value,1);

        if (homePageResponse.getCode().equals(ShoppingRetCode.SUCCESS.getCode())){
            //校验调用service后返回的response中的状态码code,如果调用服务成功在取出data返回给前端
            return new ResponseUtil<>().setData(homePageResponse.getPanelContentItemDtos());
        }
        return new ResponseUtil<>().setErrorMsg(homePageResponse.getMsg());
    }
}
